package com.cxm.weilai.controller;

import com.alibaba.fastjson.JSONObject;
import com.cxm.weilai.constants.GeneralConfigurationConstants;
import com.cxm.weilai.controller.dto.LoginDto;
import com.cxm.weilai.entity.User;
import com.cxm.weilai.result.ResponseInfo;
import com.cxm.weilai.result.ResultInfo;
import com.cxm.weilai.service.ILoginService;
import com.cxm.weilai.util.RedisUtils;
import com.cxm.weilai.util.SerialUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @program: weilai-cloud
 * @description: 登陆控制层
 * @author: ChenMan
 * @create: 2019-03-28 13:53
 */
@Controller
@RequestMapping(value = "user")
public class LoginController extends BaseController {

    private static Log logger = LogFactory.getLog(LoginController.class);

    @Autowired
    private ILoginService loginService;
    @Resource
    private RedisUtils redisUtils;


    /**
     * 用户登陆
     *
     * @param request
     * @param loginDto
     * @return
     */
    @RequestMapping(value = "userlogin", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject login(HttpServletRequest request, LoginDto loginDto) {

        // 校验验证码是否正确
//    String kaptchaCode = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//    if (!kaptchaCode.equals(loginDto.getVerificationCode())) {
//      return ResultInfo.jsonResult(ResponseInfo.LOGIN_CODE_ERROR);
//    }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginDto.getAccount(),
                loginDto.getPassword());
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException uae) {
            //用户名/密码错误
            return ResultInfo.jsonResult(ResponseInfo.USERORPWD_ERROR);
        } catch (IncorrectCredentialsException ice) {
            //用户名/密码错误
            return ResultInfo.jsonResult(ResponseInfo.USERORPWD_ERROR);
        } catch (ExcessiveAttemptsException eae) {
            //登陆次数异常，账户锁定
            return ResultInfo.jsonResult(ResponseInfo.ACCOUNT_LOCKOUT);
        } catch (AuthenticationException ae) {
            //其他异常
            return ResultInfo.jsonResult(ResponseInfo.LOGIN_ERROR);
        }

        boolean authenticated = subject.isAuthenticated();
        if (authenticated) {
            JSONObject json = new JSONObject();
            User currentUser = (User) subject.getPrincipal();
//      JSONObject menuJson = menuService.findAllMenu(currentUser.getAccount());
            JSONObject menuJson = new JSONObject();
            json.put("userInfo", currentUser);
            json.put("menuJson", menuJson);
            byte[] encode = SerialUtil.encode(json);
            try {
                // 将用户信息放在redis 中有效时间是30s   30s 之后失效
                redisUtils.set(GeneralConfigurationConstants.USERINFO_DIRECTORY + request.getRequestedSessionId(),
                        menuJson, 30 * 60);
            } catch (Exception e) {
                logger.debug(e.getMessage());
                return ResultInfo.jsonResult(ResponseInfo.LOGIN_ERROR);
            }
            return ResultInfo.jsonResult(ResponseInfo.LOGIN_SUCCESS);
        } else {
            return ResultInfo.jsonResult(ResponseInfo.LOGIN_ERROR);
        }
    }

    /**
     * 用户注册
     *
     * @param request
     * @param user
     * @return
     */
    @RequestMapping(value = "regist", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject regist(HttpServletRequest request, @RequestBody User user) {
        String registType = request.getHeader("user-agent");
//    if (registType.contains("Window")) {
//      user.setRegistType(GeneralConfigurationConstants.REGIST_TYPE_PC);
//    } else if (registType.contains("Android")) {
//      user.setRegistType(GeneralConfigurationConstants.REGIST_TYPE_ANDROID);
//    } else if (registType.contains("iPhone")) {
//      user.setRegistType(GeneralConfigurationConstants.REGIST_TYPE_IOS);
//    } else if (registType.contains("iPad")) {
//      user.setRegistType(GeneralConfigurationConstants.REGIST_TYPE_IPAD);
//    } else {
//      user.setRegistType(GeneralConfigurationConstants.REGIST_TYPE_ELSE);
//    }
        // 用户注册
        return loginService.regist(user);
//    return ResultInfo.jsonResult(ResponseInfo.LOGIN_ERROR);
    }

    /**
     * 用户退出
     * @param request
     * @return
     */
//  @RequestMapping(value="logout", method=RequestMethod.GET)
//  @ResponseBody
//  public JSONObject logout(HttpServletRequest request){
//    // 删除用户信息
//    redisUtil.remove((GeneralConfigurationConstants.USERINFO_DIRECTORY + request.getRequestedSessionId()).getBytes());
//    // shiro 退出
//    Subject subject = SecurityUtils.getSubject();
//    subject.logout();
//    return ResultInfo.jsonResult(ResponseInfo.LOGINOUT_SUCCESS);
//  }

    /**
     * 注解的使用
     *
     * @return
     */
    @RequiresRoles("admin")
    @RequiresPermissions("create")
    @RequestMapping(value = "/create")
    public String create() {
        return "Create success!";
    }

    /**
     * @return
     */
    @RequestMapping(value = "/findByName")
    @ResponseBody
    public JSONObject findByName() {
        User user = loginService.findByName(1L);
        System.out.println(ResultInfo.OK(user.toString()));
        return ResultInfo.OK(user.toString());
    }
}
